<?php
namespace Todo\Service;
use Todo\Model\Sys\UserModel;

/**
 * Created by PhpStorm.
 * User: ypp
 * Date: 2016/6/19
 * Time: 14:43
 */
class LoginService extends BaseService
{
    private static $_INSTANCE = null;

    protected $_currentUser = 0;

    public static function getInstance(){
        if(!self::$_INSTANCE) self::$_INSTANCE = new LoginService();
        return self::$_INSTANCE;
    }

    /**
     * 验证用户名密码，并返回用户详细信息
     * @param $account 账号
     * @param $password 密码
     * @return bool|mixed
     */
    public function checkLogin($account, $password){
        $userModel = new UserModel();
        $userInfo = $userModel->findOne(array('account'=>$account, 'is_del'=>0));
        if(!$userInfo){
            $this->setError('用户不存在!');
            return false;
        }

        $ep = $this->encrypt($password, $userInfo['salt']);
        if($ep != $userInfo['password']){
            $this->setError('账号或密码错误!'.$ep);
            return false;
        }

        $update = array(
            'login_count' => $userInfo['login_count'] + 1,
            'last_time'   => NOW_TIME,
            'last_ip'      => get_client_ip()
        );
        $userModel->where(array('id'=>$userInfo['id']))->save($update);

        unset($userInfo['password']);
        return $userInfo;
    }

    /**
     * 登录认证操作
     * @param $account 账号
     * @param $password 密码
     */
    public function doLogin($account, $password){
        
        LogService::getInstance()->login($account);

        $userInfo = $this->checkLogin($account, $password);
        if(!$userInfo) return false;

        //判断是否为超级管理员
        $userInfo['is_super'] = $this->checkSuper($userInfo['id']);
        if($userInfo['is_super']) define("SUPER_ADMIN", 1);
        $userInfo['roles'] = UserService::getInstance()->getUserRole($userInfo['id'],true);
        session('user', $userInfo);
        $this->_currentUser = $userInfo;

        return $userInfo;
    }

    /**
     * 注销登录
     */
    public function doLogout(){
        session('user', null);
        $this->_currentUser = null;
    }

    /** 加密密码
     * @param string $password
     * @param string $salt = ''
     * @return string
     */
    public function encrypt($password, $salt=''){
        return md5($salt. $password);
    }

    /**
     * 判断是否为超级管理员
     * @param int $userId 用户ID
     * @return bool
     */
    public function checkSuper($userId){
        return in_array($userId, C('AUTH.SUPER_USER'));
    }

    /**
     * 定向到登陆页面
     */
    public function gotoLogin($back = ''){
        if(!$back) $back = __SELF__;
        session('__back', $back);
        header('Location: '. C('AUTH.LOGIN'));
        die();
    }


    /**
     * 查询已经登录的当前用户信息
     * @param bool $foreLogin=ture是否强制到登录页面
     * @return bool|int|mixed
     */
    public function getLoginUser($foreLogin=true){
        if($this->_currentUser) return $this->_currentUser;

        $this->_currentUser = session('user');

        if($this->_currentUser['is_super']) define("SUPER_ADMIN", 1);
        if($this->_currentUser) return $this->_currentUser;

        //var_dump($this->_currentUser);die();
        if($foreLogin) $this->gotoLogin();

        return false;
    }

    /**
     * 查询当前用户信息
     * @param string|boolean $field=true 字段
     */
    public function getCurrentUser($field=true){
        $info = $this->getLoginUser(false);
        if(!$info) return false;

        return $field === true ? $info : $info[$field];
    }
}